package com.codermn.day721.udptest;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author jxau_scf
 * @date 2021/7/22 - 9:40
 */
public class UDPtest extends JFrame implements ActionListener,Runnable{

    private Container con;

    private JTextField input;

    private JTextArea showMesseage;

    private JButton SendMes;

    private DatagramSocket server = new DatagramSocket(11001);



    public UDPtest() throws SocketException{
        this.setTitle("发送方");
        this.setVisible(true);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setResizable(false);
        this.setBounds(400, 300, 400, 300);
        this.setLayout(null);
        //基本属性设置

        con = this.getContentPane();
        input = new JTextField();
        showMesseage = new JTextArea();
        SendMes = new JButton("发送");
        //初始化组件
        con.add(SendMes);con.add(input);con.add(showMesseage);
        SendMes.setBounds(0, 0, 400, 40);
        showMesseage.setBounds(0, 40, 400, 200);
        showMesseage.disable();
        input.setBounds(0, 240, 400, 30);

        SendMes.addActionListener(this);


    }
    @Override
    public void actionPerformed(ActionEvent e) {  //触发按钮监听

        try {
            DatagramPacket packet = new DatagramPacket(new byte[1024*8], 8*1024);
            packet.setData(input.getText().getBytes());
            packet.setPort(7845);
            packet.setAddress(InetAddress.getLocalHost());
            server.send(packet);                                      //创建设置并给报文放入输入框的数据
            System.out.println(new String(packet.getData()));           //发送


        } catch (SocketException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }

    @Override
    public void run() {
        while(true) {

            try {                      //同上的注释
                DatagramPacket packet = new DatagramPacket(new byte[1024*8], 8*1024);
                server.receive(packet);
                String data = packet.getAddress().getHostName()+ new String(packet.getData())+'\n';
                showMesseage.append(data);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }

    }
    public static void main(String[] args) throws SocketException {
        //UDPtest ui = new UDPtest();
        new Thread(new UDPtest()).start();
    }


}
